package com.qf.controller;

import com.qf.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 86198
 * @version V1.0
 * @Project Java_qf
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/5/27 18:35
 */
public class BaseService extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端传来的method属性
        String methodStr = req.getParameter(Constants.TAG);

        //判断获取的 methodStr 是否为空
        if (methodStr == null) {
            //如果为空给它赋值为 index
            methodStr=Constants.INDEX;
        }

        //获取大Class
        Class clazz = this.getClass();

        try {
            //通过大Class获取方法
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
            //运行此方法获取返回值
            Object results  = method.invoke(this, req, resp);
            //判断运行结果不为空
            if (results != null) {
                //将返回的结果强转为 String 类型
                String jump = (String)results;
                //判断结果第一个字符是 重定向 还是 跳转
                if (jump.startsWith(Constants.REDIRECT)) {
                    //如果为重定向截取 ：以后的字符串为要跳转的地址
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    //开始重定向
                    resp.sendRedirect(path);
                }else if (jump.startsWith(Constants.FORWARD)){
                    //如果为 跳转
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    //开始跳转
                    req.getRequestDispatcher(path).forward(req,resp);
                }else {
                    //否则直接输出到页面
                    resp.getWriter().println(jump);
                }
            }


        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }
}
